package com.deep.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.deep.common.model.dto.es.SkuEsModel;
import com.deep.search.config.ElasticsearchConfig;
import com.deep.search.constant.EsConstant;
import com.deep.search.service.ProductSaveService;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author Deep
 * @date 2022/1/24
 */
@Slf4j
@Service
public class ProductSaveServiceImpl implements ProductSaveService {

    @Qualifier("esRestClient")
    @Autowired
    private RestHighLevelClient client;

    @Override
    public boolean productUp(List<SkuEsModel> skuEsModels) throws IOException {
        // 1、批量请求
        BulkRequest bulkRequest = new BulkRequest();
        // 2、构造保存请求
        for (SkuEsModel skuEsModel : skuEsModels) {
            // 建立索引
            IndexRequest request = new IndexRequest(EsConstant.PRODUCT_INDEX);
            // 设置索引id
            request.id(skuEsModel.getSkuId().toString());
            String jsonString = JSON.toJSONString(skuEsModel);
            request.source(jsonString, XContentType.JSON);
            bulkRequest.add(request);
        }
        // 3、保存数据
        BulkResponse response = client.bulk(bulkRequest, ElasticsearchConfig.COMMON_OPTIONS);
        // 4、分析返回结果
        if (response.hasFailures()) {
            List<String> errors = Arrays.stream(response.getItems())
                    .map(item -> item.getId()).collect(Collectors.toList());
            log.error("商品上架错误：{}", errors);
            return false;
        }
        return true;
    }
}
